<template>
  <div class="max-w-4xl mx-auto space-y-6">
    <!-- 测试完成状态 -->
    <Card v-if="state === 'complete'">
      <CardHeader class="text-center">
        <CardTitle class="flex items-center justify-center gap-2">
          <CheckCircle class="w-6 h-6 text-green-500" />
          {{ $t("typingSpeedTest.testComplete") }}
        </CardTitle>
      </CardHeader>
      <CardContent class="space-y-6">
        <div class="text-center space-y-4">
          <div class="text-6xl font-bold text-primary">
            {{ stats.netWpm }}
          </div>
          <div class="text-xl text-muted-foreground">
            {{ $t("typingSpeedTest.netWpmDescription") }}
          </div>
          <div :class="`text-xl font-semibold ${rating.color}`">
            {{ rating.text }}
          </div>
          <div class="text-lg">
            {{ $t("typingSpeedTest.finalScore") }}
            <span class="font-bold text-primary">{{ score }}</span>
          </div>
        </div>

        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div class="text-center p-4 bg-muted rounded-lg">
            <div class="text-2xl font-bold">{{ stats.wpm }}</div>
            <div class="text-sm text-muted-foreground">
              {{ $t("typingSpeedTest.totalWpm") }}
            </div>
          </div>
          <div class="text-center p-4 bg-muted rounded-lg">
            <div class="text-2xl font-bold">{{ stats.netWpm }}</div>
            <div class="text-sm text-muted-foreground">
              {{ $t("typingSpeedTest.netWpm") }}
            </div>
          </div>
          <div class="text-center p-4 bg-muted rounded-lg">
            <div class="text-2xl font-bold">{{ stats.accuracy }}%</div>
            <div class="text-sm text-muted-foreground">
              {{ $t("typingSpeedTest.accuracy") }}
            </div>
          </div>
          <div class="text-center p-4 bg-muted rounded-lg">
            <div class="text-2xl font-bold">
              {{ Math.round(stats.timeElapsed) }}s
            </div>
            <div class="text-sm text-muted-foreground">
              {{ $t("typingSpeedTest.timeTaken") }}
            </div>
          </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div class="text-center p-4 bg-muted rounded-lg">
            <div class="text-xl font-bold">{{ stats.charactersTyped }}</div>
            <div class="text-sm text-muted-foreground">
              {{ $t("typingSpeedTest.totalCharacters") }}
            </div>
          </div>
          <div class="text-center p-4 bg-muted rounded-lg">
            <div class="text-xl font-bold text-green-600">
              {{ stats.correctCharacters }}
            </div>
            <div class="text-sm text-muted-foreground">
              {{ $t("typingSpeedTest.correctCharacters") }}
            </div>
          </div>
          <div class="text-center p-4 bg-muted rounded-lg">
            <div class="text-xl font-bold text-red-600">
              {{ stats.errorCharacters }}
            </div>
            <div class="text-sm text-muted-foreground">
              {{ $t("typingSpeedTest.errorCharacters") }}
            </div>
          </div>
          <div class="text-center p-4 bg-muted rounded-lg">
            <div class="text-xl font-bold">{{ stats.cpm }}</div>
            <div class="text-sm text-muted-foreground">
              {{ $t("typingSpeedTest.cpm") }}
            </div>
          </div>
        </div>

        <div class="flex gap-4">
          <Button
            @click="resetTest"
            variant="outline"
            class="flex-1 border-2 border-slate-300 hover:border-blue-500 hover:bg-blue-50 hover:text-blue-700 transition-all duration-200"
          >
            <RotateCcw class="w-4 h-4 mr-2" />
            {{ $t("typingSpeedTest.retest") }}
          </Button>
          <Button
            @click="handleComplete"
            class="flex-1 bg-gradient-to-r from-green-500 to-emerald-500 text-white hover:from-green-600 hover:to-emerald-600 shadow-md hover:shadow-lg transition-all duration-200"
          >
            {{ $t("typingSpeedTest.saveResult") }}
          </Button>
        </div>
      </CardContent>
    </Card>

    <!-- 测试中计时器 -->
    <Card v-if="state === 'testing'">
      <CardContent class="pt-6">
        <div class="flex justify-between items-center mb-4">
          <div class="flex items-center gap-4">
            <div class="flex items-center gap-2">
              <Timer class="w-4 h-4" />
              <span class="font-mono text-lg">{{ timeLeft }}s</span>
            </div>
            <Badge
              :variant="
                timeLeft > 30
                  ? 'secondary'
                  : timeLeft > 10
                  ? 'default'
                  : 'destructive'
              "
            >
              {{
                timeLeft > 30
                  ? $t("typingSpeedTest.timeAmple")
                  : timeLeft > 10
                  ? $t("typingSpeedTest.timeWarning")
                  : $t("typingSpeedTest.timeUrgent")
              }}
            </Badge>
          </div>
          <div class="flex items-center gap-4">
            <div v-if="userInput.length > 0" class="text-sm">
              <Zap class="w-4 h-4 inline mr-1" />
              {{ stats.netWpm }} {{ $t("typingSpeedTest.netWpm") }}
            </div>
            <div v-if="userInput.length > 0" class="text-sm">
              <Target class="w-4 h-4 inline mr-1" />
              {{ stats.accuracy }}% {{ $t("typingSpeedTest.accuracy") }}
            </div>
          </div>
        </div>
        <Progress
          :model-value="
            testDuration > 0
              ? ((testDuration - timeLeft) / testDuration) * 100
              : 0
          "
        />
      </CardContent>
    </Card>

    <!-- 主测试区域 -->
    <Card>
      <!-- 准备状态 -->
      <template v-if="state === 'ready'">
        <CardHeader class="text-center">
          <CardTitle class="flex items-center justify-center gap-2">
            <Keyboard class="w-6 h-6 text-blue-500" />
            {{ $t("typingSpeedTest.title") }}
          </CardTitle>
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="text-center space-y-4">
            <p class="text-muted-foreground">
              {{ $t("typingSpeedTest.instruction", { testDuration }) }}
            </p>
            <div class="flex justify-center gap-4">
              <Badge variant="outline">
                <Timer class="w-3 h-3 mr-1" />
                {{ $t("typingSpeedTest.duration", { testDuration }) }}
              </Badge>
              <Badge variant="outline">
                <Target class="w-3 h-3 mr-1" />
                {{ $t("typingSpeedTest.accuracyFirst") }}
              </Badge>
              <Badge variant="outline">
                <Zap class="w-3 h-3 mr-1" />
                {{ $t("typingSpeedTest.speedMatters") }}
              </Badge>
            </div>
            <div
              class="bg-blue-50 border border-blue-200 rounded-lg p-4 text-sm text-blue-800"
            >
              <h4 class="font-semibold mb-2">
                {{ $t("typingSpeedTest.scoringTitle") }}
              </h4>
              <ul class="text-left space-y-1">
                <li>
                  <strong>{{ $t("typingSpeedTest.scoringRule1_b") }}</strong
                  >{{ $t("typingSpeedTest.scoringRule1_t") }}
                </li>
                <li>
                  <strong>{{ $t("typingSpeedTest.scoringRule2_b") }}</strong
                  >{{ $t("typingSpeedTest.scoringRule2_t") }}
                </li>
                <li>
                  <strong>{{ $t("typingSpeedTest.scoringRule3_b") }}</strong
                  >{{ $t("typingSpeedTest.scoringRule3_t") }}
                </li>
                <li>
                  <strong>{{ $t("typingSpeedTest.scoringRule4_b") }}</strong
                  >{{ $t("typingSpeedTest.scoringRule4_t") }}
                </li>
              </ul>
            </div>
          </div>
          <div class="text-center">
            <Button
              size="lg"
              @click="startTest"
              class="bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
            >
              <Keyboard class="w-5 h-5 mr-2" />
              {{ $t("typingSpeedTest.startTest") }}
            </Button>
          </div>
        </CardContent>
      </template>

      <!-- 测试中状态 -->
      <template v-else-if="state === 'testing'">
        <CardContent class="space-y-6">
          <div class="space-y-4">
            <h3 class="font-semibold">
              {{ $t("typingSpeedTest.enterTextPrompt") }}
            </h3>
            <div
              class="p-4 bg-muted rounded-lg font-mono text-lg leading-relaxed select-none"
            >
              <span
                v-for="(char, index) in testText.split('')"
                :key="index"
                :class="getCharClass(index)"
              >
                {{ char }}
              </span>
            </div>
          </div>

          <div class="space-y-2">
            <label class="font-semibold">{{
              $t("typingSpeedTest.yourInput")
            }}</label>
            <textarea
              ref="inputRef"
              v-model="userInput"
              @input="handleInputChange"
              class="w-full h-32 p-4 border rounded-lg font-mono text-lg resize-none focus:outline-none focus:ring-2 focus:ring-primary"
              :placeholder="$t('typingSpeedTest.startTyping')"
              :disabled="state !== 'testing'"
            />
          </div>

          <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
            <div class="p-3 bg-muted rounded-lg">
              <div class="text-xl font-bold">{{ userInput.length }}</div>
              <div class="text-sm text-muted-foreground">
                {{ $t("typingSpeedTest.charactersTyped") }}
              </div>
            </div>
            <div class="p-3 bg-muted rounded-lg">
              <div class="text-xl font-bold">{{ testText.length }}</div>
              <div class="text-sm text-muted-foreground">
                {{ $t("typingSpeedTest.totalCharacters") }}
              </div>
            </div>
            <div class="p-3 bg-muted rounded-lg">
              <div class="text-xl font-bold">
                {{
                  testText.length > 0
                    ? Math.round((userInput.length / testText.length) * 100)
                    : 0
                }}%
              </div>
              <div class="text-sm text-muted-foreground">
                {{ $t("typingSpeedTest.progress") }}
              </div>
            </div>
            <div class="p-3 bg-muted rounded-lg">
              <div class="text-xl font-bold">{{ stats.netWpm }}</div>
              <div class="text-sm text-muted-foreground">
                {{ $t("typingSpeedTest.currentNetWpm") }}
              </div>
            </div>
          </div>
        </CardContent>
      </template>
    </Card>

    <!-- 测试说明 -->
    <Card>
      <CardContent class="pt-6">
        <h3 class="font-semibold mb-2">
          {{ $t("typingSpeedTest.testInstructionsTitle") }}
        </h3>
        <ul class="text-sm text-muted-foreground space-y-1">
          <li>{{ $t("typingSpeedTest.instruction1", { testDuration }) }}</li>
          <li>{{ $t("typingSpeedTest.instruction2") }}</li>
          <li>{{ $t("typingSpeedTest.instruction3") }}</li>
          <li>
            <strong>{{ $t("typingSpeedTest.instruction4_b") }}</strong
            >{{ $t("typingSpeedTest.instruction4_t") }}
          </li>
          <li>
            <strong>{{ $t("typingSpeedTest.instruction5_b") }}</strong
            >{{ $t("typingSpeedTest.instruction5_t") }}
          </li>
          <li>{{ $t("typingSpeedTest.instruction6") }}</li>
        </ul>
      </CardContent>
    </Card>
  </div>
</template>

<script setup>
// 导入 Vue 相关功能
import { ref, computed, onUnmounted } from "vue";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

// 导入 Lucide Vue 图标
import {
  CheckCircle,
  RotateCcw,
  Timer,
  Target,
  Zap,
  Keyboard,
} from "lucide-vue-next";

// 定义 props
const props = defineProps({
  onComplete: {
    type: Function,
    required: true,
  },
});

// 状态管理
const state = ref("ready"); // ready | testing | complete
const testText = ref("");
const userInput = ref("");
const startTime = ref(0);
const endTime = ref(0);
const timeLeft = ref(60);
const timerInterval = ref(null);
const inputRef = ref(null);

const testDuration = 60; // 测试时长(秒)

// 测试文本样本
const sampleTexts = [
  "人工智能技术正在快速发展，它将改变我们的生活方式和工作方式。机器学习和深度学习算法使得计算机能够从数据中学习并做出智能决策。",
  "现代社会信息技术的发展日新月异，互联网已经成为人们日常生活中不可或缺的一部分。云计算、大数据、物联网等技术正在重塑整个社会。",
  "教育是社会发展的基石，优质的教育资源应该让每个人都能享受到。在线教育平台的兴起为知识传播提供了新的渠道和方式。",
  "环境保护是当今世界面临的重大挑战之一。可持续发展理念要求我们在追求经济增长的同时，也要保护好我们赖以生存的地球环境。",
  "科技创新是推动经济社会发展的重要动力。从移动支付到共享经济，从人工智能到区块链技术，创新正在深刻改变着我们的世界。",
];

// 开始测试
const startTest = () => {
  const randomText =
    sampleTexts[Math.floor(Math.random() * sampleTexts.length)];
  testText.value = randomText;
  userInput.value = "";
  state.value = "testing";
  startTime.value = Date.now();
  endTime.value = 0;
  timeLeft.value = testDuration;

  timerInterval.value = setInterval(() => {
    timeLeft.value -= 1;
    if (timeLeft.value <= 0) {
      clearInterval(timerInterval.value);
      state.value = "complete";
      endTime.value = Date.now();
    }
  }, 1000);

  nextTick(() => {
    inputRef.value?.focus();
  });
};

// 处理输入变化
const handleInputChange = (e) => {
  userInput.value = e.target.value;

  // 检查是否完成输入
  if (userInput.value.length >= testText.value.length) {
    if (timerInterval.value) {
      clearInterval(timerInterval.value);
    }
    state.value = "complete";
    endTime.value = Date.now();
  }
};

// 重置测试
const resetTest = () => {
  state.value = "ready";
  testText.value = "";
  userInput.value = "";
  startTime.value = 0;
  endTime.value = 0;
  timeLeft.value = testDuration;
  if (timerInterval.value) {
    clearInterval(timerInterval.value);
    timerInterval.value = null;
  }
};

// 获取字符样式
const getCharClass = (index) => {
  if (index < userInput.value.length) {
    if (userInput.value[index] === testText.value[index]) {
      return "text-green-600 bg-green-100 dark:bg-green-900/30";
    } else {
      return "text-red-600 bg-red-100 dark:bg-red-900/30";
    }
  } else if (index === userInput.value.length) {
    return "bg-blue-200 dark:bg-blue-800 text-foreground animate-pulse";
  }
  return "text-muted-foreground";
};

// 计算统计数据
const stats = computed(() => {
  let timeElapsed;
  if (endTime.value > 0) {
    timeElapsed = (endTime.value - startTime.value) / 1000;
  } else if (startTime.value > 0) {
    timeElapsed = (Date.now() - startTime.value) / 1000;
  } else {
    timeElapsed = 0.1;
  }

  timeElapsed = Math.max(0.1, timeElapsed);

  const charactersTyped = userInput.value.length;

  // 计算正确字符数
  let correctCharacters = 0;
  for (
    let i = 0;
    i < Math.min(userInput.value.length, testText.value.length);
    i++
  ) {
    if (userInput.value[i] === testText.value[i]) {
      correctCharacters++;
    }
  }

  const wordsTyped = userInput.value.trim().length;
  const wpm = Math.round(charactersTyped / 5 / (timeElapsed / 60));
  const cpm = Math.round(charactersTyped / (timeElapsed / 60));

  let accuracy = 0;
  if (charactersTyped > 0) {
    accuracy = Math.round((correctCharacters / charactersTyped) * 100);
  }

  const errorCharacters = charactersTyped - correctCharacters;
  const netWpm = Math.max(
    0,
    Math.round(
      (correctCharacters / 5 - errorCharacters / 5) / (timeElapsed / 60)
    )
  );

  return {
    wpm: Math.max(0, Math.min(wpm, 999)),
    netWpm: Math.max(0, Math.min(netWpm, 999)),
    cpm: Math.max(0, Math.min(cpm, 9999)),
    accuracy: Math.max(0, Math.min(accuracy, 100)),
    wordsTyped: Math.max(0, wordsTyped),
    charactersTyped: Math.max(0, charactersTyped),
    correctCharacters: Math.max(0, correctCharacters),
    errorCharacters: Math.max(0, errorCharacters),
    timeElapsed: Math.max(0, timeElapsed),
  };
});

// 计算得分
const score = computed(() => {
  const { netWpm, accuracy } = stats.value;

  let score = netWpm;

  // 准确率奖励/惩罚
  if (accuracy >= 98) {
    score *= 1.2;
  } else if (accuracy >= 95) {
    score *= 1.1;
  } else if (accuracy >= 90) {
    score *= 1.05;
  } else if (accuracy < 80) {
    score *= 0.8;
  } else if (accuracy < 85) {
    score *= 0.9;
  }

  return Math.max(0, Math.min(100, Math.round(score)));
});

// 获取评级
const rating = computed(() => {
  const { netWpm } = stats.value;
  if (netWpm >= 80)
    return {
      text: t("typingSpeedTest.ratingMaster"),
      color: "text-purple-500",
    };
  if (netWpm >= 60)
    return {
      text: t("typingSpeedTest.ratingProfessional"),
      color: "text-yellow-500",
    };
  if (netWpm >= 45)
    return {
      text: t("typingSpeedTest.ratingAdvanced"),
      color: "text-green-500",
    };
  if (netWpm >= 30)
    return {
      text: t("typingSpeedTest.ratingIntermediate"),
      color: "text-blue-500",
    };
  if (netWpm >= 20)
    return {
      text: t("typingSpeedTest.ratingBeginner"),
      color: "text-gray-500",
    };
  return { text: t("typingSpeedTest.ratingNovice"), color: "text-orange-500" };
});

// 完成测试
const handleComplete = () => {
  const result = {
    id: Date.now().toString(),
    testType: "typing",
    score: score.value,
    completedAt: new Date(),
    duration: Math.max(1, Math.round(stats.value.timeElapsed)),
    details: {
      wpm: stats.value.wpm,
      netWpm: stats.value.netWpm,
      cpm: stats.value.cpm,
      accuracy: stats.value.accuracy,
      wordsTyped: stats.value.wordsTyped,
      charactersTyped: stats.value.charactersTyped,
      correctCharacters: stats.value.correctCharacters,
      errorCharacters: stats.value.errorCharacters,
      timeElapsed: stats.value.timeElapsed,
      rating: rating.value.text,
      testText:
        testText.value.length > 0
          ? testText.value.substring(0, 100) +
            (testText.value.length > 100 ? "..." : "")
          : t("typingSpeedTest.noTestText"),
      userInput:
        userInput.value.length > 0
          ? userInput.value.substring(0, 100) +
            (userInput.value.length > 100 ? "..." : "")
          : t("typingSpeedTest.noInput"),
      totalQuestions: 1,
      correctAnswers: stats.value.accuracy >= 85 ? 1 : 0,
      averageTimePerQuestion: stats.value.timeElapsed,
      averageTime: stats.value.timeElapsed,
      totalRounds: 1,
    },
  };
  props.onComplete(result);
};

// 组件卸载时清理定时器
onUnmounted(() => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value);
  }
});
</script>
